import React, { Component, useState, useEffect } from "react";
import { Table, Input, InputNumber, Popconfirm, Form, message, Button, Select, Space, ConfigProvider } from 'antd';
// import from './index.css';
import { Axios } from 'toolkit';
import zhCN from 'antd/es/locale/zh_CN';  // 引入中文包
import { PlusCircleTwoTone, SearchOutlined } from '@ant-design/icons';
import Item from 'antd/lib/list/Item';
import globalStoreData from '@/store';

const { Option } = Select;


interface Item {
  // indexStartNum: number,
  id: string;
  code: string;
  name: string;
  districtId: string;
  orgType: string,
  orgTypeName: string;
  status: string;
  createTime: string;
  updateTime: string;
  operation: string;
}

interface Result {
  message: string,
  succeed: boolean,
  data: Page
}

interface Page {
  "toatlePage": number,
  "toatleCount": number,
  "pageSize": number,
  "values": Item[]
}
// interface SearchInfo {
//   conditionText: string | undefined, // 名称或编号
//   districtId: string | undefined, // 区划id
//   status: string | undefined// 状态

// }

interface EditableCellProps extends React.HTMLAttributes<HTMLElement> {
  editing: boolean;
  dataIndex: string;
  title: any;
  data: any;
  inputType: 'number' | 'text';
  record: Item;
  index: number;
  children: React.ReactNode;
}


const EditableCell: React.FC<EditableCellProps> = React.memo(({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {

  let data = JSON.parse(globalStoreData.getStore('SysEnumList'));
  let districtId:any = [];
  let orgType:any = [];
  let status:any = [];
  data.forEach((item:any) => {
    if(item.title === 'district') {
      districtId.push(item);
    }
    if(item.title === 'orgType') {
      orgType.push(item);
    }
    if(item.title === 'Status') {
      status.push(item);
    }
  })
  // console.log(districtId)
  // console.log(orgType)
  // console.log(status)
  const _getInputNode = (inputType: string) => {
    if (inputType === 'number') {
      return <InputNumber />;
    }
    if (inputType === 'districtId') {
      return (<Select
        placeholder="请选择"
        optionFilterProp="children"
        onChange={() => { }}
        onFocus={() => { }}
        onBlur={() => { }}
        options={
          districtId.map(item => {
            return {
              label: item.name,
              value: item.code
            }
          })
        }
      
      >
        {/* {districtId.map( value => (
          <Option key={value.code} value={value.code}> {value.name} </Option>
        ))} */}
      </Select>);
    }
    if (inputType === 'orgType') {
      return (<Select
        placeholder="请选择"
        optionFilterProp="children"
        onChange={() => { }}
        onFocus={() => { }}
        onBlur={() => { }}
        options={
          orgType.map(item => {
            return {
              label: item.name,
              value: item.code
            }
          })
        }
      // }
      >
        {/* {
          orgType.map( value => (
            <Option key={value.code} value={value.code}> {value.name} </Option>
          ))
        } */}
      </Select>);
    }
    if (inputType === 'status') {
      return (<Select
        // style={{ width: 200 }}
        placeholder="请选择"
        optionFilterProp="children"
        onChange={() => { }}
        onFocus={() => { }}
        onBlur={() => { }}
        options={
          status.map(item => {
            return {
              label: item.name,
              value: item.code
            }
          })
        }
      >
        {/* {
          status.map( value => (
            <Option key={value.code} value={value.code}> {value.name} </Option>
          ))
        } */}
      </Select>);
    }
    return <Input />;
  }
  const inputNode = _getInputNode(inputType);
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{ margin: 0 }}
          rules={[
            {
              required: true,
              message: `请输入${title}!`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
          children
        )}
    </td>
  );
});

const OrganizationPage = () => {
  // const [droplist, setDroplist] = useState([])
  const searchRef = React.useRef<any>();
  const districtIdRef = React.useRef<any>();
  const statusRef = React.useRef<any>();
  const [form] = Form.useForm();
  const [data, setData] = useState<Item[]>();
  const [page, setPage] = useState<number>(0);
  const [total, setTotal] = useState<number>(0);
  const [editingKey, setEditingKey] = useState('');
  // const [mechanism, setMechanism] = useState('');
  const [districtId, setDistrictId] = useState('') // 搜索区划
  const [status, setStatus] = useState('') // 搜索状态
  // const [status,setStatus] = useState('')
  const [searchValue, setSearchValue] = useState(); // 搜索框
  const pageSize: number = 5;

  let droplist = JSON.parse(globalStoreData.getStore('SysEnumList'));
  let sysdistrictId:any = [];
  let sysorgType:any = [];
  let sysstatus:any = [];
  droplist.forEach((item:any) => {
    if(item.title === 'district') {
      sysdistrictId.push(item);
    }
    if(item.title === 'orgType') {
      sysorgType.push(item);
    }
    if(item.title === 'Status') {
      sysstatus.push(item);
    }
  })
  console.log(sysdistrictId)
  console.log(sysorgType)
  console.log(sysstatus)
  let sysdistrictOptions = sysdistrictId.map(item => {
    return {
      label: item.name,
      value: item.code
    }
  })
  let sysorgTypeOptions:any = sysorgType.map(item => {
    return {
      label: item.name,
      value: item.code
    }
  })
  let sysstatusOptions:any = sysstatus.map(item => {
      return {
        label: item.name,
        value: item.code
      }
    })

console.log(sysdistrictOptions)

  const isEditing = (record: Item) => record.id === editingKey; // 设置 编辑状态 和 不编辑状态的变量

  const edit = (record: Item) => {
    form.setFieldsValue({ ...record });
    setEditingKey(record.id);
  };

  const cancel =() => {
    setEditingKey('');
    if (editingKey === 'add') {
      let newData: any = [...data];
      newData.splice(0, 1);
      setData(newData)
    }
  }


  useEffect(() => {
    query();

    return () => { }
  }, [page,searchValue,districtId,status])

  

  const query = () => {
    let searchInfo = () => {
      if (searchValue) {
        
      }
    }
    // ?conditionText=${searchValue}&districtId=${districtId}&status=${status}
    Axios.post(`/organizationList`, {
      limit: pageSize,
      pageNum: page
    }).then(res => {
      let reslut: Result = res.data;
      if (!reslut.succeed) {
        message.error(reslut.message);
        return;
      }
      let resultData = reslut.data.values.map((item: Item, index: number) => {
        return {
          ...item, index: index + 1
        }
      })
      setData(resultData);
      setTotal(reslut.data.toatleCount);
      // console.log(page)

    }).catch(error => {
      console.error(error);
      message.error(error.message);
    })
  }


  // 点击 新增 出现输入框
  const openAdd = async (): Promise<void> => {
    try {
      if (editingKey !== '') {
        message.error('请先保存');
        return;
      }
      const row: any = {
        id: 'add', // 这里也是 add
        code: '',
        name: '',
        districtId: '',
        orgType: 0,
        status: 0,
        createTime: '',
        updateTime: '',
        operation: '',
      };

      const newData = [...data];
      newData.unshift(row)
      // newData.splice(data.length, 1, row);
      setData(newData);
      // editingKye这个变量 设置为add
      setEditingKey('add');
      
      form.resetFields();//保存后清空表单内容

    } catch (errInfo) {
    }
  };

  // 编辑 和 新增
  const save = async (id: string) => {
    // 监听 数据 变化字段
    const row = (await form.validateFields()) as Item;
    // 拷贝 原始数据 复杂的 数据 可用 loadsh
    const newData = [...data];
    // 获取 新增 或编辑数据在原始数据中 下标
    const index = newData.findIndex(item => id === item.id);
    // 构建后端需要的 参数对象
    let params: any = {
      ...newData[index],
      ...row
    }
    
    // 判断是不是新增  
    if (id !== 'add') {
      // id不为add就是编辑
      Axios.post('/updateOrganizationById', params, 
      {headers: {
        'DISTRICT_CODE': 1111
      }}).then((res: any) => {
        if (res.data.succeed) {
          message.success('编辑成功');
          newData.splice(index, 1, params);
          setData(newData);
          setEditingKey('');
          
          query();
        } else {
          message.error(res.data.message)
        }
      }).catch((error) => {

      })
    } else {
      // id是add为新增
      // 去除id 
      delete params.id;
      Axios.post('/addOrganization', params, {headers: {
        'DISTRICT_CODE': 1111
      }}).then((res: any) => {
        if (res.data.succeed) {
          message.success('新增成功');
          newData.splice(index, 1, params);
          setData(newData);
          setEditingKey('');
          query();
        } else {
          message.error(res.data.message)
        }
      }).catch((error) => {
        message.error(error);
      })
    }

  };

  const del = async (id: string) => {
    // Axios.post('').then(respone=>{
    //   let result =  response.data; 
    // })
    // .catch(error=>{
    //   console.log(error)
    // })
    try {
      const res = await Axios.post('/removeOrganization', { "id": id })
      let result = res.data

      if (result.succeed == true) {
        const newData = [...data];
        const index = newData.findIndex((item) => id === item.id);
        newData.splice(index, 1);
        // const item = newData[index];
        // newData.splice(index, 1, {
        //   ...item,
        //   ...row,
        // });
        query();
        setData(newData);
        setEditingKey('');
      } else {

        message.error(result.message);
      }
    } catch (error) {
      console.error(error);
    }

  };

  // setData(data.filter(id => id !== record.id))
  // };

  const columns = [
    { title: '行号', dataIndex: 'index', width: '5%', 
    render: (text, record: TableItem, index) => {
      let rowNum = page * pageSize  + index + 1;
      return (<div>{rowNum}</div>)
    }},
    { title: '机构编码', dataIndex: 'code', width: '10%', editable: true },
    { title: '机构名称', dataIndex: 'name', width: '10%', editable: true },
    { title: '所属区划', dataIndex: 'districtId', width: '10%', editable: true,
      // render: (text, record: Item, index) => {
      //   let tmpRecode = record;
      //   const editable = isEditing(record);
        // console.log('打印吸'+sysdistrictOptions.filter(item => item.value === tmpRecode.districtId).label)
        // const index = sysdistrictOptions.findIndex(item => item.value === tmpRecode.districtId);
        // console.log(index)
        // sysdistrictOptions.findIndex((value, index, item) => {
          
        // })
      //   return (editable ? (
      //     <Select   defaultValue={record.districtId} options={sysdistrictOptions} onSelect={(value: string) => {
      //       tmpRecode.districtId = value;
      //       console.log(value);
      //     }} ></Select >
      //   ) :(<span>
      //      {sysdistrictOptions.find(item => item.value === tmpRecode.districtId).label}
      //   </span>))
      // }
    },
    { title: '机构类型', dataIndex: 'orgType', width: '10%', editable: true,
      // render: (value: number, record: Item) => {
      //   record.find(record => record.orgType === value).orgTypeName
      // }
      // render: (text, record: Item, index) => {
      //   let tmpRecode = record;
      //   const editable = isEditing(record);
      //   return (editable ? (
      //     <Select   defaultValue={record.orgType} options={sysorgTypeOptions} onSelect={(value: string) => {
      //       tmpRecode.orgType = value;
      //       console.log(value);
      //     }}>
      //     </Select >
      //   ) :(<span>
      //     {record.orgTypeName}
      //   </span>))
      // }
    
    },
    {
      title: '状态', dataIndex: 'status', width: '7%', editable: true,
      render: (v: number, record: status) =>
        v === 1 ? (
          <span >禁用</span>
        ) : (
          <span >启用</span>
        ),
    },
    { title: '创建时间', dataIndex: 'createTime', width: '15%', },
    { title: '更新时间', dataIndex: 'updateTime', width: '15%', },
    {
      title: '操作', dataIndex: 'operation', width: '8%',
      // 点击新增editable为true
      render: (_: any, record: Item) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <a href="javascript:;" onClick={() => save(record.id)} style={{ marginRight: 8 }}>
              保存
            </a>
            <a onClick={cancel}>取消</a>
          </span>
        ) : (
            <Space>
              <a disabled={editingKey !== ''} onClick={() => edit(record)}>
                编辑
            </a>
              <Popconfirm title="确认删除吗？" onConfirm={() => del(record.id)} okText="确定" cancelText="取消">
                <a>删除</a>
              </Popconfirm>

            </Space>
          );
      },
    },
  ];

  const _getInputType = React.useCallback((dataIndex: string) => {
    if (dataIndex === 'agdistrictIde') {
      return 'number';
    }
    if (dataIndex === 'districtId') {
      return 'districtId';
    }
    if (dataIndex === 'orgType') {
      return 'orgType';
    }
    if (dataIndex === 'status') {
      return 'status';
    }
    return 'text';
  }, [])

  const mergedColumns = columns.map(col => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: Item) => ({
        record,
        // 在这控制
        inputType: _getInputType(col.dataIndex),
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });

  return (
    <ConfigProvider locale={zhCN}>
    <div>
      {/* 这里双向绑定啊 ，双向绑定后 当你点击收缩的时候  你在去取值，传给后端就行了啊*/}
      <Space className="div-search" style={{ margin: '20px 0' }}>
        <Input
          style={{ width: '200px' }}
          value={searchValue}
          ref={searchRef}
          onChange={(e) => {
            setSearchValue(e.currentTarget.value)
          }}
          placeholder="请输入机构编码或机构名称"
        />

        所划区划：
        <Select style={{ width: '200px' }}
        ref={districtIdRef}
        value={districtId}
        onChange={(value) => {
          setDistrictId(value)
        }}
        options={sysdistrictOptions}
        >
          
        </Select>
        状态：
        <Select options={sysstatusOptions} style={{ width: '200px' }} 
        ref={statusRef}
        value={status}
        onChange={(value) => {
          setStatus(value)
        }}
        
        >
        </Select>
        <Button type="primary" icon={<SearchOutlined />} onClick={() => {
          // console.log("mechanism:", mechanism)
          // console.log(districtId)
          // console.dir(searchRef.current.props.value)
          // setSearchInfo()
          // setSearchValue(searchRef)
          // console.dir(searchRef)
          // console.dir(districtIdRef)
          setSearchValue(searchRef.current.state.value)
          setDistrictId(districtIdRef.current.props.value)
          setStatus(statusRef.current.props.value)
          
        }}>
          搜索
        </Button>
      </Space >
      <div className="div-add">
        <Button type="primary" onClick={() => openAdd()} icon={<PlusCircleTwoTone />} style={{ marginBottom: '10px' }}>
          新建
        </Button>
        {/* <Button type="primary" onClick={() => { sys() }} icon={<PlusCircleTwoTone />} style={{ marginBottom: '10px', marginLeft: '16px' }}>
          点一下
        </Button> */}
      </div>
      <Form form={form} component={false}>
        <Table rowKey={(recode) => recode.id}
          style={{
            overflow: 'hidden',
            whiteSpace: 'nowrap',
            textOverflow: 'ellipsis',
            cursor: 'pointer'
          }}
          size="middle"
          components={{
            body: {
              cell: EditableCell,
            },
          }}
          dataSource={data}
          columns={mergedColumns}
          rowClassName="editable-row"
          pagination={{
            showTotal: function showTotal(total) {
              return `总共 ${total} 条`;
            },
            pageSize: pageSize,
            onChange: (page, pageSize) => {
              setPage(page - 1);
            },
            // total: data?.length
            total: total,
            
            showQuickJumper:true

            // pageSize: data.pageSize,
            // total: data.toatleCount

          }}
        />
      </Form>
    </div>
    </ConfigProvider>
  );
};


export default OrganizationPage;